$(document).ready(function(){ 
	
	var Buttons = new Array();
	var ButtonsStr = new Array();
	
	for(var i=0; i<4; i++) {
  		Buttons[i] = jQuery.makeArray(explode( ',', $('input#buttons'+(i+1)).val() ) ) ;
	}
	
	RefreshButtons();


  	$(".r").sortable({
		placeholder: "mceIcon",
  		opacity: 0.9,
  		tolerance: "pointer",
  		connectWith : ".r",
  		
  		stop: function(event, ui) { 
  			
			for(var i=0; i<4; i++) {
				Buttons[i] = $('#buttons'+(i+1)+'_row').sortable('toArray');
				$('input#buttons'+(i+1)).val(Buttons[i].join(",")); 
			}
  		}

  	});  	
	   	
  	
	function RefreshButtons(){
		
		for(var i=0; i<4; i++) {
	  		ButtonsStr[i] = Buttons[i].join(",");	
		}
		
		$.post(
			'ajax.index.php?option=com_joieditor', 
			{ 
				task: "refresh_buttons",
				buttons1: ButtonsStr[0],
				buttons2: ButtonsStr[1],
				buttons3: ButtonsStr[2],
				buttons4: ButtonsStr[3]
			},
			
			function(data){
				
				for(var i=0; i<4; i++) {
					var x = 'data.row1';
   					$("#buttons"+(i+1)+"_row").html(data[i]);
		    		$('input#buttons'+(i+1)).val(ButtonsStr[i]);

				}
		   
		  	}, 
			  
	  		"json"
	  	);
  }
	  	
	    $('input.check_but').change( function(){

				var button = $(this).attr("title");

				if($(this).is(":checked")){
					Buttons[0].push(button);
				}
				else{
					for(var i=0; i<4; i++) {
						if(in_array(button, Buttons[i])){
							Buttons[i].remove(button);
						}	
					}
				}
				
				RefreshButtons();
	    	
	    });
	    
	    
		Array.prototype.remove=function(s){
			for (i=0; i < this.length; i++){
				if (s == this[i]){
					this.splice(i, 1);
					--i;
				}
			}
		}
		
		
		function explode( delimiter, string ) {    
	 
		    var emptyArray = { 0: '' };
		 
		    if ( arguments.length != 2
		        || typeof arguments[0] == 'undefined'
		        || typeof arguments[1] == 'undefined' )
		    {
		        return null;
		    }
		 
		    if ( delimiter === ''
		        || delimiter === false
		        || delimiter === null )
		    {
		        return false;
		    }
		 
		    if ( typeof delimiter == 'function'
		        || typeof delimiter == 'object'
		        || typeof string == 'function'
		        || typeof string == 'object' )
		    {
		        return emptyArray;
		    }
		 
		    if ( delimiter === true ) {
		        delimiter = '1';
		    }
		 
		    return string.toString().split ( delimiter.toString() );
		}
		
		
		function in_array(needle, haystack, strict) { 
		 
		    var found = false, key, strict = !!strict;
		 
		    for (key in haystack) {
		        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
		            found = true;
		            break;
		        }
		    }
		 
		    return found;
		}

   
}); 